<template>
  <div class="page-container relative">
    <BaseCollapse title="基础信息">
      <DynamicForm :config="dyConfig" :questions="dyQuestions" ref="baseRef" />
    </BaseCollapse>
    <BaseCollapse title="迁移文件信息">
      <DynamicForm :config="dyFileConfig" :questions="dyFileQuestions" ref="boxRef" />
      <DynamicTable :tables="dyTable" :config="dyTableConfig" ref="fileRef">
        <template #isReceive="{ record }">
          <a-select class="w-full" v-model:value="record.isReceive">
            <a-select-option :value="1">是</a-select-option>
            <a-select-option :value="0">否</a-select-option>
          </a-select>
        </template>
      </DynamicTable>
    </BaseCollapse>
    <BaseCollapse title="迁移信息">
      <DynamicForm :config="dyMsgConfig" :questions="dyMsgQuestions" ref="msgRef" />
    </BaseCollapse>
    <!-- <BaseCollapse v-if="['CONFIRM'].includes(state.showType)" title="迁移接收确认">
      <DynamicTable :tables="dyReceiveTable" :config="dyReceiveTableConfig" :icons="dyReceiveIcons" ref="receiveRef" />
    </BaseCollapse> -->
    <BaseCollapse v-if="['VIEW', 'CONFIRM'].includes(state.showType)" title="迁移位置确认">
      <DynamicTable :tables="dyPositionTable" :config="dyPositionTableConfig" ref="positionRef">
        <template #targetLocationTitle="{ column }">
          <span><i class="mr-1 text-red-500">*</i>{{ column.title }}</span>
        </template>
        <template #targetLocation="{ record }">
          <a-tree-select
            :tree-data="state.folderData"
            :field-names="{ label: 'name', value: 'id' }"
            v-model:value="record.targetLocation"
            class="w-full"
            allow-clear
            show-search
            placeholder="请选择"
            tree-default-expand-all
            tree-node-filter-prop="name"
          />
        </template>
      </DynamicTable>
    </BaseCollapse>
    <ApprovalDetail v-if="['VIEW', 'AUDIT', 'RECEIVE'].includes(state.showType) && query.processInstanceId" :config="approvalConfig" @back="approvalGoBack"></ApprovalDetail>
    <div class="space-x-2 w-full text-center my-4">
      <a-button v-if="state.showType !== 'AUDIT'" @click="cancel">返回</a-button>
      <a-button v-if="['ADD', 'EDIT'].includes(state.showType)" @click="submit(0)">暂存</a-button>
      <a-button v-if="['ADD', 'RECEIVE', 'CONFIRM', 'EDIT'].includes(state.showType)" type="primary" @click="submit(1)">提交</a-button>
      <a-button v-if="['VIEW'].includes(state.showType) && [1, 3].includes(state.archiveStatus)" type="primary" @click="handleEdit">编辑</a-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { createVNode, getCurrentInstance, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { DynamicForm, DynamicTable } from '@/components/public-template';
import ApprovalDetail from '@/components/approval-details/index.vue';
import BaseCollapse from '@/components/common/BaseCollapse/index.vue';
import indexService from './index.service';
import { useRoute, useRouter } from 'vue-router';
import { Api, transferAudit, transferAutoProduct, transferConfirm, transferGet, transferReceive, transferSave } from '@/config/api/archivesFileTransfer';
import { Api as ApiResource } from '@/config/api/resourceFileInfo';
import { filter } from 'rxjs/operators';
import { DYNAMICLOCALTABLE, SEARCHSERVE, SELECTSERVE } from '@/mixins/subject/subject-types';
import { message, Modal } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { downloadFile } from '@/utils/useDownload';
import { folderfindCanUseTree } from '@/config/api/archives';
import { advancedQueryPreview } from '@/config/api/searchManage';
import { throttle } from 'xe-utils';
import { formInfoStore } from '@/store/modules/form';

const { query } = useRoute();

const state = reactive({
  showType: 'ADD', // enum 'ADD' 'VIEW' 'AUDIT' 'RECEIVE' 'CONFIRM'
  archiveStatus: null, // 档案状态
  folderData: [] // 档案目录
});
const baseRef = ref(null);
const boxRef = ref(null);
const fileRef = ref(null);
const msgRef = ref(null);
const receiveRef = ref(null);
const positionRef = ref(null);
const commentRef = ref(null);
const route = useRoute();
const router = useRouter();
state.showType = route.query.showType as string;
const approvalConfig: any = ref({
  title: '审批流程',
  showBackBtn: true, //显示返回按钮
  showAgreeBtn: true, //显示同意按钮
  showGoBackBtn: true, // 显示退回按钮
  showRejectBtn: true // 显示拒绝按钮
});

const approvalGoBack = (cb: any) => {
  cb?.();
};

const dyConfig: any = {
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const dyFileConfig: any = reactive({
  name: 'migrationTable',
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  isView: ['ADD', 'EDIT'].includes(state.showType) ? false : true,
  cancelSave: true
});
const dyMsgConfig: any = reactive({
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  isView: ['ADD', 'EDIT'].includes(state.showType) ? false : true,
  cancelSave: true
});
const dyCommentConfig: any = {
  labelCol: 8,
  wrapperCol: 22,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const dyTableConfig: any = reactive({
  name: 'migrationTable',
  queryUrl: ['ADD', 'EDIT'].includes(state.showType) ? Api.transferListFrom : Api.transferListBill,
  protType: 'post',
  scroll: { x: 1920 },
  autoSearch: false,
  params: ['ADD', 'EDIT'].includes(state.showType) ? { ids: [] } : { billId: route.query.id, isInfo: state.showType == 'VIEW' }
});
const dyReceiveTableConfig: any = reactive({
  name: 'receiveTable'
});
const dyPositionTableConfig: any = reactive({
  name: 'positionTable'
});
const { proxy }: any = getCurrentInstance();
const dyQuestions: any = reactive(indexService.getQuestions());
const formStore1 = formInfoStore();
formStore1.setQuestions(indexService.getFileQuestions());
const dyFileQuestions = formStore1.getQuestions;
// const dyFileQuestions: any = reactive(['ADD', 'EDIT'].includes(state.showType) ? indexService.getFileQuestions() : indexService.getViewFileQuestions());
const formStore2 = formInfoStore();
formStore2.setQuestions(indexService.getMsgQuestions());
const dyMsgQuestions = formStore1.getQuestions;
// const dyMsgQuestions: any = reactive(['ADD', 'EDIT'].includes(state.showType) ? indexService.getMsgQuestions() : indexService.getViewMsgQuestions());
const dyCommentQuestions: any = reactive(indexService.getCommentQuestions({ showType: state.showType }));
const dyTable: any = reactive(indexService.getTables({ showType: state.showType }));
const dyReceiveTable: any = reactive(indexService.getReceiveTables({ showType: state.showType }));
const dyPositionTable: any = reactive(indexService.getPositionTables({ showType: state.showType }));
const dyReceiveIcons: any = reactive(indexService.getReceiveIcons({ showType: state.showType, handleReceiveImport }));

onMounted(() => {
  if (state.showType == 'ADD') {
    transferAutoProduct({}).then((result) => {
      if (result.success) {
        // 基本信息
        const data = result.data;
        dyQuestions.forEach((item) => (item.value = data[item.key]));
      }
    });
  } else if (['AUDIT', 'CONFIRM', 'RECEIVE', 'VIEW', 'EDIT'].includes(state.showType)) {
    transferGet(route.query.id).then((result) => {
      if (result.success) {
        // 基本信息
        const data = result.data;
        state.archiveStatus = result.data.status;
        dyQuestions.forEach((item) => (item.value = data[item.key]));
        // 迁移文件信息
        dyFileQuestions.forEach((item) => {
          if (item.key == 'archivesFileBox' && data.archivesFileBox) {
            // 档案盒查看
            item.value = data.archivesFileBox.map((obj) => obj.code).join('；');
          } else if (item.key == 'boxIds' && data.archivesFileBox) {
            // 档案盒编辑
            item.value = data.archivesFileBox.map((obj) => obj.id);
            // 获取档案盒的文件
            proxy.$NotificationFormSub.pushParams({ key: SELECTSERVE, value: { value: item.value, name: 'migrationTable' } });
          }
        });
        // 迁移接收确认
        if (receiveRef.value) receiveRef.value.dataList.value = data.attachments;
        // 迁移位置确认
        if (positionRef.value) positionRef.value.dataList.value = data.list;
        // 迁移信息
        dyMsgQuestions.forEach((item) => (item.value = data[item.key]));
      }
    });
  }
  // 获取档案目录
  getArchivesFolder();
  if (['VIEW'].includes(state.showType)) {
    approvalConfig.value.showBackBtn = false;
    approvalConfig.value.showAgreeBtn = false;
    approvalConfig.value.showGoBackBtn = false;
    approvalConfig.value.showRejectBtn = false;
  }
});
// 监听档案盒form
const subscribeSubForm = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === SELECTSERVE && item.value.name == 'migrationTable') {
      console.log('item', item);
      const params = {
        ids: item.value.value
      };
      proxy.$NotificationFormSub.pushParams({
        key: SEARCHSERVE,
        value: params,
        state: { name: 'migrationTable' }
      });
    }
  });
// 监听迁移接收确认table
const subscribeSubPub = proxy.$NotificationPubSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === DYNAMICLOCALTABLE) {
      if (item.value.part.state?.type == 'delete') {
        Modal.confirm({
          title: '是否确认删除？',
          icon: createVNode(ExclamationCircleOutlined),
          okText: '确定',
          cancelText: '取消',
          onOk() {
            receiveRef.value.dataList.value = receiveRef.value.dataList.value.filter((itemTable) => itemTable.id !== item.value.data.id);
          },
          onCancel() {}
        });
      } else if (item.value.part.state?.type == 'download') {
        const url = `${ApiResource.resourceViewFile}/${item.value.data.id}`;
        downloadFile(url);
      } else if (item.value.part.state?.name == 'LOCAL_PREVIEW') {
        advancedQueryPreview({ id: item.value.data.id, needRecord: false }).then((res) => {
          if (res.success && res.data) {
            window.open(res.data, '_blank');
          }
        });
      } else if (item.value.part?.type == 'local') {
        previewFile(item.value.data.fileId || item.value.data.id);
      }
    }
  });
// 获取档案目录
function getArchivesFolder() {
  if (state.showType !== 'CONFIRM') return;
  folderfindCanUseTree(null).then((result) => {
    if (result.success) {
      state.folderData = dealData(result.data);
    }
  });
}
// 档案目录
function dealData(param) {
  return param.map((item) => ({
    ...item,
    children: item.children ? dealData(item.children) : []
  }));
}
// 迁移接收确认导入
function handleReceiveImport(result) {
  if (Array.isArray(result)) {
    receiveRef.value.dataList.value.push(...result);
  } else {
    receiveRef.value.dataList.value.push(result);
  }
}

function cancel() {
  router.go(-1);
}
function handleEdit() {
  state.showType = 'EDIT';
  dyFileConfig.isView = false;
  dyMsgConfig.isView = false;
  dyTableConfig.params = ['ADD', 'EDIT'].includes(state.showType) ? { ids: [] } : { billId: route.query.id, isInfo: state.showType == 'VIEW' };
  dyTableConfig.queryUrl = ['ADD', 'EDIT'].includes(state.showType) ? Api.transferListFrom : Api.transferListBill;
}
// 提交 op操作（0=暂存；1=提交）
const submit = throttle(async function (op) {
  if (['ADD', 'EDIT'].includes(state.showType)) {
    // 基本信息
    const baseData = baseRef.value.getDataFrom();
    // 迁移文件信息
    let isError;
    await boxRef.value.isValidateFields(op == 0 ? [] : null).catch((error) => {
      isError = true;
      console.warn(error);
    });
    const boxData = boxRef.value.getDataFrom();
    const fileData = fileRef.value.dataList.value;
    // 迁移信息
    await msgRef.value.isValidateFields(op == 0 ? [] : null).catch((error) => {
      isError = true;
      console.warn(error);
    });
    const msgData = msgRef.value.getDataFrom();
    const params = {
      op,
      ...baseData,
      ...boxData,
      ...msgData,
      fileListIds: fileData.map((item) => item.id)
    };
    state.showType == 'EDIT' && Object.assign(params, { id: route.query.id });
    console.log('params', params);
    if (isError) return;
    transferSave(params).then((result) => {
      if (result.success) {
        message.success('提交成功');
        router.go(-1);
      }
    });
  } else if (state.showType == 'AUDIT') {
    const commentData = commentRef.value.getDataFrom();
    const params = {
      billId: route.query.id,
      ...commentData
    };
    transferAudit(params).then((result) => {
      if (result.success) {
        message.success('提交成功');
        router.go(-1);
      }
    });
  } else if (state.showType == 'RECEIVE') {
    const commentData = commentRef.value.getDataFrom();
    const list = receiveRef.value.dataList.value.map((item) => ({
      fileId: item.id,
      name: item.name,
      size: item.size,
      createdTime: item.createdTime,
      suffix: item.suffix
    }));
    const params = {
      billId: route.query.id,
      list,
      ...commentData
    };
    transferReceive(params).then((result) => {
      if (result.success) {
        message.success('提交成功');
        router.go(-1);
      }
    });
  } else if (state.showType == 'CONFIRM') {
    const list = positionRef.value.dataList.value.map((item) => {
      return {
        id: item.id,
        archiveBoxId: item.archiveBoxId,
        targetLocation: item.targetLocation
      };
    });
    if (!list.every((item) => item.targetLocation)) return message.warning('必填项新存放地点不可为空');
    const params = {
      billId: route.query.id,
      list
    };
    transferConfirm(params).then((result) => {
      if (result.success) {
        message.success('提交成功');
        router.go(-1);
      }
    });
  }
}, 3000);
// 预览附件
function previewFile(fileId) {
  const params = { id: fileId, expires: 2, timeUnit: 'HOURS' };
  proxy.$Http.api(ApiResource.getPreviewFileUrl, params, 'post').then((data: any) => {
    if (data.success && data.data) {
      let a = document.createElement('a');
      a.href = data.data;
      a.target = '_blank';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
  });
}
onBeforeUnmount(() => {
  subscribeSubForm && subscribeSubForm.unsubscribe();
  subscribeSubPub && subscribeSubPub.unsubscribe();
  proxy.$NotificationFormSub.clearParams();
  proxy.$NotificationPubSub.clearParams();
});
</script>

<style lang="less" scoped>
:deep(.ant-form-item-control-input-content) {
  word-wrap: break-word;
}
</style>
